
<template>
  <div id="expQuestion hp100">
    <Alert type="warning" show-icon>单位的课件不允许添加个人题目</Alert>

    <Button
      @click="addExperimentQues"
      :icon="currQuestionTotal > 0 ? 'ios-refresh' : 'ios-add'"
      type="primary"
      :disabled="isDisable || status"
    >
      <span v-if="currQuestionTotal > 0">更新题目</span>
      <span v-else>添加题目</span>
    </Button>
    <!-- <WarningTip placement="right" content="单位的课件不允许添加个人题目"></WarningTip> -->
    <Poptip
      confirm
      transfer
      title="确认清空？"
      @on-ok="delExperimentQues"
      style="float: right"
    >
      <Button
        type="error"
        icon="ios-trash-outline"
        v-if="currQuestionTotal > 0"
        :disabled="isDisable || status"
        >清空</Button
      >
    </Poptip>
    <Divider dashed />
    <div v-if="showDataList && !questionLoading">
      <QuestionList
        :data="currQuestionData"
        :showScore="false"
        :showWriteUp="true"
      ></QuestionList>
      <Row style="text-align: center; margin-top: 10px">
        <Page
          :total="currQuestionTotal"
          show-total
          :current="queryCurrQuestionInfo.pageIndex"
          show-elevator
          :page-size="10"
          placement="top"
          @on-change="currQuestionOnChange"
          @on-page-size-change="currQuestionChangePageSize"
        />
      </Row>
    </div>
    <div
      style="position: relative; min-height: 300px"
      v-if="showDefImg || questionLoading"
    >
      <no-data :loading="questionLoading" absolute></no-data>
    </div>
    <Modal
      v-model="questionModal.show"
      width="1200"
      :title="questionModal.title"
      ok-text="提交"
      cancel-text="取消"
      @on-ok="submitQuestion"
      :loading="questionModal.loading"
      :mask-closable="false"
      class="fix-height-modal"
      id="questionModal"
    >
      <Row style="word-break: breal-all" class="questionModal-Content">
        <Col span="11">
          <Card dis-hover>
            <div slot="title">
              <p style="display: inline">所有题目</p>
              <Tag color="green">{{ questionTotal }}</Tag>
              <div class="flex-end mt10">
                <Input
                  v-model.trim="queryQuestionInfo.description"
                  :placeholder="$t('name')"
                  style="width: 100px"
                  clearable
                  @on-change="questionOnChange(1)"
                />
                <Cascader
                  change-on-select
                  :data="treeDirectionData"
                  v-model="queryQuestionInfo.typeCode"
                  placeholder="请选择方向类型"
                  clearable
                  @on-change="changeCascader"
                  style="width: 200px"
                  class="ml10"
                ></Cascader>
                <!-- <Select filterable
                                    v-model="queryQuestionInfo.typeCode"
                                    placeholder="请选择知识点"
                                    style="width: 170px;"
                                    multiple
                                    clearable
                                    :max-tag-count="1"
                                    class="ml10"
                                    @on-change="questionOnChange(1)"
                                >
                                    <Option
                                        v-for="item in typeCodeObj"
                                        :key="item.dictid"
                                        :value="item.dictid"
                                        :title="item.dictname"
                                        >{{ item.dictname }}</Option
                                    >
                                </Select> -->
                <Select filterable
                  v-model="queryQuestionInfo.difficulty"
                  placeholder="请选择难度"
                  clearable
                  style="width: 100px"
                  class="ml10"
                  @on-change="questionOnChange(1)"
                >
                  <Option value="simple">简单</Option>
                  <!--<Option  value="commonly">一般</Option>-->
                  <Option value="medium">中等</Option>
                  <Option value="hard">较难</Option>
                </Select>
                <Select filterable
                  v-model="queryQuestionInfo.modeCode"
                  placeholder="请选择题型"
                  clearable
                  style="width: 100px"
                  class="ml10"
                  @on-change="questionOnChange(1)"
                >
                  <Option :value="1">单选</Option>
                  <Option :value="2">多选</Option>
                  <Option :value="3">判断</Option>
                  <Option :value="4">填空</Option>
                </Select>
                <!--<Button @click="initQueryQuesInfo" type="error" icon="ios-trash-outline">清空过滤</Button>-->
              </div>
            </div>
            <div class="flex-between">
              <Button type="primary" size="small" @click="selectAllQuestion"
                >选择所有</Button
              >
              <CreateQuestion @on-success="refreshQues"></CreateQuestion>
            </div>
            <Divider dashed />
            <QuestionList
              :data="allQuestionData"
              :showChecked="true"
              :showScore="false"
              @on-select="selectQuestion"
            >
            </QuestionList>
            <Row>
              <Page
                :total="questionTotal"
                show-total
                :page-size-opts="imagePageSizeOpts"
                :current="queryQuestionInfo.pageIndex"
                :page-size="10"
                placement="top"
                @on-change="questionOnChange"
                @on-page-size-change="questionChangePageSize"
                style="text-align: center; margin-top: 10px"
              />
            </Row>
          </Card>
        </Col>
        <Col span="11" offset="1">
          <Card dis-hover class="card_height">
            <div slot="title">
              <p style="display: inline">已选题目</p>
              <Tag color="green">{{ selectQuestionData.length }}</Tag>
            </div>
            <Button type="primary" size="small" @click="removeAllQuestion"
              >清空所有</Button
            >
            <Divider dashed />
            <QuestionList
              :data="selectQuestionData"
              :showActions="true"
              :showScore="false"
            >
              <template slot="action" slot-scope="{ question, index }">
                <Button
                  type="error"
                  size="small"
                  @click="removeQuestion(question, index)"
                  style="padding: 0px 3px"
                  ><Icon type="ios-trash"
                /></Button>
              </template>
            </QuestionList>
          </Card>
        </Col>
      </Row>
    </Modal>
  </div>
</template>

<script>
import {
    addExpQuestion,
    modifyExpQuestion,
    delExpQuestion,
    queryExpQuestionDetail,
    delExpQuestionS
} from '@/api/selfStudy/courseExp';
import { queryObjectiveList, queryObjectiveAnswerList } from '@/api/question';
import CreateQuestion from './create-question';
import QuestionList from '@/components/question-list';
import { typeAndDirectionMixin } from '@/mixin/study';
export default {
    name: 'expQuestion',
    components: { CreateQuestion, QuestionList },
    mixins: [typeAndDirectionMixin],
    props: ['ecId', 'status', 'isPublic', 'isOwn'],
    data() {
        return {
            isDisable: true,
            imagePageSizeOpts: [10, 20],
            USER_ID: '',
            currQuestionData: [],
            questionLoading: false,
            allQuestionData: [],
            selectQuestionData: [],
            questionTotal: 0,
            currQuestionTotal: 0,
            queryQuestionInfo: {
                pageIndex: 1,
                pageSize: 10,
                typeCode: []
            },
            queryCurrQuestionInfo: {
                pageIndex: 1,
                pageSize: 10,
                order: 'asc',
                sortBy: 'orderNo'
            },
            questionListLoading: false,
            questionModal: {
                show: false,
                title: '添加题目',
                loading: true
            },
            typeCodeObj: [],
            allObjectQuestion: [],
            showDataList: true,
            showDefImg: false
        };
    },
    watch: {},
    filters: {},
    computed: {},
    mounted() {
        this.queryCurrQuestionInfo.ecid = this.ecId;
        this.getExperimentQues();
    },
    beforeDestroy() {},
    methods: {
        initQueryQuesInfo() {
            this.queryQuestionInfo = {
                pageIndex: 1,
                pageSize: 10,
                typeCode: []
            };
        },
        async addExperimentQues() {
            this.queryQuestionInfo = {
                pageIndex: 1,
                pageSize: 10,
                typeCode: []
            };
            if (this.currQuestionTotal > 0) {
                await this.getAllExperimentQues();
            }
            this.queryObjectQuestionList();
            //	    	this.selectQuestionData = JSON.parse(JSON.stringify(this.currQuestionData));
            this.questionModal.show = true;
        },
        getExperimentQues() {
            this.questionLoading = true;
            queryExpQuestionDetail(this.queryCurrQuestionInfo)
                .then((data) => {
                    if (data.code == 1) {
                        let quesDetailList = data.data.items.map((ques) => {
                            //获取题目详情
                            let question = ques.detail;
                            if (question) {
                                question.name = question.description;
                                question.description = question.explanation;
                                // if (question.modeCode == 3) {
                                //     this.$set(question, 'answers', [
                                //         {
                                //             isRight: question.answers[0].isRight == 0 ? 0 : 1,
                                //             answerID: '1',
                                //             description: '正确'
                                //         },
                                //         {
                                //             isRight: question.answers[0].isRight == 1 ? 0 : 1,
                                //             answerID: '2',
                                //             description: '错误'
                                //         }
                                //     ]);
                                // }
                                // question.description = this.escape2Html(question.description, true);
                                //this.queryObjectiveAnswerList(question);
                                return Object.assign(question, ques);
                            } else {
                                ques.modeCode = '5'; //  删除后，默认给一个modeCode 5
                                ques.description = '该题目已被删除';
                                return ques;
                            }
                        });
                        this.currQuestionData = quesDetailList;
                        this.currQuestionTotal = data.data.total;
                        this.isDisable = false;
                        if (this.currQuestionData.length > 0) {
                            this.showDataList = true;
                            this.showDefImg = false;
                            this.$emit('on-finish', true);
                        } else {
                            this.showDataList = false;
                            this.showDefImg = true;
                        }
                    } else {
                        this.currQuestionData = [];
                        this.$Message.error(data.message);
                    }
                    this.questionLoading = false;
                })
                .catch((err) => {
                    console.log(err);
                    this.questionLoading = false;
                });
        },
        getAllExperimentQues() {
            return new Promise((resolve, reject) => {
                let params = {
                    pageIndex: 1,
                    pageSize: 2147483647,
                    ecid: this.ecId
                };
                queryExpQuestionDetail(params)
                    .then((data) => {
                        if (data.code == 1) {
                            let quesDetailList = data.data.items.map((ques) => {
                                //获取题目详情
                                let question = ques.detail;
                                ques.name = question.description;
                                ques.description = question.explanation;
                                if (question) {
                                    question.questionID = question.id;
                                    // if (question.modeCode == 3) {
                                    //     this.$set(question, 'answers', [
                                    //         {
                                    //             isRight: question.answers[0].isRight == 0 ? 0 : 1,
                                    //             answerID: '1',
                                    //             description: '正确'
                                    //         },
                                    //         {
                                    //             isRight: question.answers[0].isRight == 1 ? 0 : 1,
                                    //             answerID: '2',
                                    //             description: '错误'
                                    //         }
                                    //     ]);
                                    // }
                                    //this.queryObjectiveAnswerList(question);
                                    return Object.assign(question, ques);
                                } else {
                                    ques.description = '该题目已被删除或查看权限不足';
                                    return ques;
                                }
                            });
                            this.selectQuestionData = quesDetailList;
                            resolve();
                            //	            this.currQuestionTotal = data.data.total;
                        } else {
                            this.selectQuestionData = [];
                            this.$Message.error(data.message);
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            });
        },
        cancleLoading(name) {
            this[name].loading = false;
            setTimeout(() => {
                this[name].loading = true;
            });
        },
        submitQuestion() {
            if (this.selectQuestionData.length == 0) {
                this.$Message.warning('请选择题目');
                this.cancleLoading('questionModal');
                return;
            }
            let questionList = this.selectQuestionData.map((ques, index) => {
                return {
                    orderNo: index,
                    questionId: ques.questionID
                };
            });
            let data = {
                ecid: this.ecId,
                questionList: questionList
            };
            if (this.currQuestionTotal <= 0) {
                //创建题目
                addExpQuestion(data)
                    .then((data) => {
                        // console.log(res)
                        if (data.code == 1) {
                            this.$Message.info(data.message);
                            this.questionModal.loading = false;
                            this.questionModal.show = false;
                            this.selectQuestionData = [];
                            this.getExperimentQues();
                        } else {
                            this.cancleLoading('questionModal');
                            this.$Message.error(data.message);
                        }
                    })
                    .catch((err) => {
                        this.cancleLoading('questionModal');
                        console.log(err);
                    });
            } else {
                this.delExperimentQues().then((data) => {
                    modifyExpQuestion(this.ecId, questionList)
                        .then((data) => {
                            // console.log(res)
                            if (data.code == 1) {
                                this.$Message.info(data.message);
                                this.questionModal.loading = false;
                                this.questionModal.show = false;
                                this.selectQuestionData = [];
                                this.getExperimentQues();
                            } else {
                                this.cancleLoading('questionModal');
                                this.$Message.error(data.message);
                            }
                        })
                        .catch((err) => {
                            this.cancleLoading('questionModal');
                            console.log(err);
                        });
                });
            }
        },
        delExperimentQues() {
            return new Promise((resolve, reject) => {
                delExpQuestion(this.ecId)
                    .then((data) => {
                        // console.log(res)
                        if (data.code == 1) {
                            this.getExperimentQues();
                            resolve();
                        } else {
                            this.$Message.error(data.message);
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            });
        },
        queryAllObjectQuestion() {
            let params = {
                pageIndex: 1,
                pageSize: 2147483647
            };
            this.questionLoading = true;
            queryObjectiveList({}, params).then((data) => {
                if (data.code === 1) {
                    if (data.data.items && data.data.items.length > 0) {
                        let allObjectQuestion = data.data.items;
                        allObjectQuestion.forEach((question) => {
                            question.questionID = question.id;
                        });
                        this.allObjectQuestion = allObjectQuestion;
                        this.getExperimentQues();
                    } else {
                        this.allObjectQuestion = [];
                    }
                }
            });
        },
        getDisabledStatus() {
            return (this.isPublic == '1' || !this.isOwn) && item.visibility == 'private';
        },
        queryObjectQuestionList() {
            let copeQueryQuestionInfo = JSON.parse(JSON.stringify(this.queryQuestionInfo));
            let { pageIndex, pageSize, ...data } = copeQueryQuestionInfo;
            let params = {
                pageIndex,
                pageSize
            };
            data.typeCode = data.typeCode[data.typeCode.length - 1];
            data.applicationList=[3]// 查询实验用途为3 的客观题
            // data.typeCode = data.typeCode.join(',');
            queryObjectiveList(data, params).then((data) => {
                if (data.code === 1) {
                    if (data.data.items && data.data.items.length > 0) {
                        this.allQuestionData = data.data.items;
                        this.allQuestionData.forEach((ques) => {
                            ques.name = ques.description;
                            ques.description = ques.explanation;
                            this.$set(ques, '_disabled', this.getDisabledStatus(ques));
                            // ques.description = this.escape2Html(ques.description, true);
                            ques.questionID = ques.id;
                            this.$set(ques, '_checked', false);
                            let selectQuestionIds = this.selectQuestionData.map(
                                (ques) => ques.questionID
                            );
                            if (selectQuestionIds.findIndex((id) => ques.questionID == id) != -1) {
                                ques._checked = true;
                            }
                            if (ques.modeCode == 3) {
                                this.$set(ques, 'answers', [
                                    {
                                        isRight: ques.answers[0].isRight == 0 ? 0 : 1,
                                        answerID: '1',
                                        description: '正确'
                                    },
                                    {
                                        isRight: ques.answers[0].isRight == 1 ? 0 : 1,
                                        answerID: '2',
                                        description: '错误'
                                    }
                                ]);
                            }
                            //this.queryObjectiveAnswerList(ques);
                        });
                    } else {
                        this.allQuestionData = [];
                    }
                    this.questionTotal = data.data.total;
                }
            });
        },
        refreshQues() {
            this.queryAllObjectQuestion();
            this.initQueryQuesInfo();
            this.questionOnChange(1);
        },
        changeCascader(value) {
            this.queryQuestionInfo.typeCode = value;
            this.questionOnChange(1);
        },
        questionOnChange(val) {
            this.queryQuestionInfo.pageIndex = val;
            //回到顶部
            document
                .getElementById('questionModal')
                .getElementsByClassName('ivu-modal-body')[0].scrollTop = 0;
            this.queryObjectQuestionList();
        },
        questionChangePageSize(val) {
            this.queryQuestionInfo.pageSize = val;
            this.queryObjectQuestionList();
        },
        currQuestionOnChange(val) {
            this.queryCurrQuestionInfo.pageIndex = val;
            this.getExperimentQues();
        },
        currQuestionChangePageSize(val) {
            this.queryCurrQuestionInfo.pageSize = val;
            this.getExperimentQues();
        },
        selectAllQuestion(e) {
            this.allQuestionData.forEach((ques) => {
                if (!ques._checked) {
                    if (this.isPublic == '1' && ques.visibility == 'private') {
                        return;
                    }
                    this.selectQuestion(true, ques);
                }
            });
        },
        selectQuestion(status, val) {
            if (this.isPublic == '1' && val.visibility == 'private') {
                //单位的课件不允许使用个人题目
                this.$Message.warning('单位的课件不允许选择个人资源');
                return;
            }
            if (status) {
                //单个选择
                this.selectQuestionData.push(val);
                val._checked = true;
            } else {
                let index = this.selectQuestionData.findIndex(
                    (ques) => ques.questionID == val.questionID
                );
                this.removeQuestion(val, index);
            }
            //	    	else{ //全选
            //	    		let questionIDs = this.selectQuestionData.map(ques => ques.questionID);
            //	    		questionList.forEach(ques => {
            //	    			if(!questionIDs.includes(ques.questionID)){
            //	    				this.selectQuestionData.push(ques);
            //	    				ques._checked = true;
            //	    			}
            //	    		})
            //	    	}
            //	    	console.log(this.selectQuestionData);
        },
        cancelSelectQuestion(questionList, val) {
            if (val) {
                //单个取消
                let index = this.selectQuestionData.findIndex(
                    (ques) => ques.questionID == val.questionID
                );
                this.selectQuestionData.splice(index, 1);
                val._checked = false;
            } else {
                //全部取消
                questionList.forEach((ques) => {
                    let index = this.selectQuestionData.findIndex(
                        (ques) => ques.questionID == ques.questionID
                    );
                    if (index != -1) {
                        ques._checked = false;
                        this.selectQuestionData.splice(index, 1);
                    }
                });
            }
            console.log(this.selectQuestionData);
        },
        handleClose(e, currQuesId) {
            //软件列表中的索引
            const index = this.allQuestionData.findIndex(function(value, index, arr) {
                return value.questionID == currQuesId;
            });
            if (index != -1) {
                this.$refs.questionTb.toggleSelect(index);
            }
        },
        queryObjectiveAnswerList(question) {
            queryObjectiveAnswerList(question.questionID).then((data) => {
                if (data.code == 1) {
                    let answ = this.sortQuestionAnswer(data.data.answers);
                    this.$set(question, 'answers', answ);
                    if (question.modeCode == 3) {
                        this.$set(question, 'answers', [
                            {
                                isRight: question.answers[0].isRight == 0 ? 0 : 1,
                                answerID: '1',
                                description: '正确'
                            },
                            {
                                isRight: question.answers[0].isRight == 1 ? 0 : 1,
                                answerID: '2',
                                description: '错误'
                            }
                        ]);
                    }
                }
            });
        },
        //对题目答案进行排序
        sortQuestionAnswer(answer) {
            if (!answer) {
                return;
            } else if (answer.length > 0 && answer[0].no) {
                answer.sort(function(a, b) {
                    return parseInt(a.no) - parseInt(b.no);
                });
            }
            return answer;
        },
        removeAllQuestion() {
            this.selectQuestionData = [];
            this.allQuestionData.forEach((ques) => {
                ques._checked = false;
            });
        },
        removeQuestion(ques, index) {
            //删除已选题目
            this.selectQuestionData.splice(index, 1);
            let question = this.allQuestionData.filter(
                (question) => question.questionID == ques.questionID
            );
            if (question.length > 0) {
                this.$set(question[0], '_checked', false);
            }
        },
        delQuestion(ques, index) {
            delExpQuestionS(this.ecId, ques.id)
                .then((data) => {
                    if (data.code == 1) {
                        this.$Message.info(data.message);
                        this.getExperimentQues();
                    } else {
                        this.$Message.warning(data.message);
                    }
                })
                .catch((error) => {
                    this.$Message.error(error);
                });
        },
        parseDescription(question) {
            if (!question.answers) {
                return;
            }
            let description;
            description = question.description.replace(
                /\{\{.*?\}\}/g,
                `<span class='quesBlank' disabled style='width:40px;padding:0px 5px;outline:none;box-shadow:none;border:none;border-bottom:1px solid rgb(168,166,200);color:#2d8cf0'></span>`
            );
            let el = document.createElement('div');
            el.innerHTML = description;
            let answersEle = el.getElementsByClassName('quesBlank');
            let answers = question.answers || question.keAnswerTOS;
            Array.from(answersEle).forEach((ele, index) => {
                answersEle[index].innerHtml = answers[index].explanation;
            });
            return el.innerHTML;
        },
        escape2Html(str, needReplace) {
            if (!str) {
                return;
            }
            let repStr = str.replace(/\{\{.*?\}\}/g, '___');
            let arrEntities = {
                lt: '<',
                gt: '>',
                nbsp: ' ',
                amp: '&',
                quot: '"'
            };
            if (needReplace) {
                repStr = repStr.replace(/&(amp|lt|gt|quot|nbsp);/gi, function(all, t) {
                    return arrEntities[t];
                });
            }
            return repStr;
        }
    },
    destroyed() {}
};
</script>
<style scoped>
#questionModal /deep/ .ivu-card-body {
  width: 100%;
  max-height: calc(70vh - 115px);
  overflow: hidden auto;
}
#questionModal .card_height /deep/ .ivu-card-body {
  width: 100%;
  max-height: calc(70vh - 73px);
  overflow: hidden auto;
}
.questionModal-Content{
  height: calc(70vh - 36px);
}
#questionModal /deep/ .ivu-card-bordered{
  min-height: 60vh;
}
</style>

